package cn.itcast.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;

@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {
	
	//注入service
	@Autowired
	private StandardService standardService;
	
	
	// 模型驱动
	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}

	@Action(value="standard_save",
			results={@Result(name="success",type="redirect",
				location="./pages/base/standard.html")})
	
	public String save() {
		
		System.out.println("添加收派标准...");
		standardService.save(standard);
		return SUCCESS;
	}
	//属性驱动从页面传入两个参数page  rows
		private int page;
		private int rows;
		
		public void setPage(int page) {
			this.page = page;
		}

		public void setRows(int rows) {
			this.rows = rows;
		}
		
		//分页列表查询
		@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
		public String queryPage() {
			
			//PageRequest实现Pageable接口
			Pageable pageable=new PageRequest(page-1,rows);
			Page<Standard> pageData=standardService.findPageData(pageable);
			
			//返回数据到客户端 需要total和rows
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("total",pageData.getTotalElements());
			map.put("rows", pageData.getContent());
			//然后将这两个数据 压住值栈的最顶层 ,然后在客户端自动取出来
			//将map转换为json 使用我们导入进来的struts2-json-plugin插件
			ActionContext.getContext().getValueStack().push(map);
			return SUCCESS;
			
		}
		//查询所有取派信息
		@Action(value="standard_findAll", results={@Result(name="success",type="json")})
		public String findAll() {
			//调用service层
			List<Standard> list=standardService.findAll();
			ActionContext.getContext().getValueStack().push(list);
			return SUCCESS;
			
		}
		
}
